package com.hsgene.product.controller;

import com.hsgene.common.exception.CommonErrorCode;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.product.dto.QuerySetMealDto;
import com.hsgene.product.dto.SetMealDto;
import com.hsgene.product.exception.ProductErrorCode;
import com.hsgene.product.service.ElasticsearchService;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.index.reindex.BulkByScrollTask;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @description:
 * @projectName: hdas-geneshop-server
 * @package: com.hsgene.product.controller
 * @author: maodi
 * @createDate: 2018/10/23 9:01
 * @version: 1.0
 * Copyright: Copyright (c) 2018
 */
@RestController
@RequestMapping("/v1.0/genetic/testing/products")
public class ElasticsearchController {

    private static Logger LOGGER = LogManager.getLogger(ElasticsearchController.class);

    @Autowired
    ElasticsearchService elasticsearchService;

    /**
     * @param setMealDto 套餐数据
     * @return
     * @description 新增数据
     * @author maodi
     * @createDate 2018/10/22 15:09
     */
    @PostMapping
    public ApiResult<NullObject> add(@RequestBody SetMealDto setMealDto) {
        try {
            String id = setMealDto.getId();
            if (StringUtils.isBlank(id)) {
                return ApiResult.fail(ProductErrorCode.PACKAGE_ID_IS_NULL);
            }
            RestStatus status = elasticsearchService.addSetMealDto(setMealDto);
            if (status.getStatus() == RestStatus.CREATED.getStatus() || status.getStatus() == RestStatus.OK.getStatus
                    ()) {
                return ApiResult.succ();
            } else {
                return ApiResult.fail(ProductErrorCode.ADD_SET_MEAL_TO_ELASTICSEARCH_IS_ERROR, status.name());
            }
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.ADD_SET_MEAL_TO_ELASTICSEARCH_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.ADD_SET_MEAL_TO_ELASTICSEARCH_IS_ERROR);
        }
    }

    /**
     * @param id 套餐id
     * @return
     * @description 根据id删除套餐数据
     * @author maodi
     * @createDate 2018/10/22 15:09
     */
    @DeleteMapping("{package_id}")
    public ApiResult<NullObject> delete(@PathVariable("package_id") String id) {
        try {
            RestStatus status = elasticsearchService.deleteSetMealDto(id);
            if (status.getStatus() == RestStatus.OK.getStatus()) {
                return ApiResult.succ();
            } else {
                return ApiResult.fail(ProductErrorCode.DELETE_SET_MEAL_FROM_ELASTICSEARCH_IS_ERROR, status.name());
            }
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.DELETE_SET_MEAL_FROM_ELASTICSEARCH_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.DELETE_SET_MEAL_FROM_ELASTICSEARCH_IS_ERROR);
        }
    }

    /**
     * @param setMealDto 套餐数据
     * @return
     * @description 修改套餐数据
     * @author maodi
     * @createDate 2018/10/22 15:09
     */
    @PutMapping("{package_id}")
    public ApiResult<NullObject> update(@PathVariable("package_id") String id, @RequestBody SetMealDto setMealDto) {
        try {
            //不可修改套餐和机构名字
            setMealDto.setName(null);
            setMealDto.setOrgs(null);

            if (StringUtils.isBlank(id)) {
                return ApiResult.fail(ProductErrorCode.PACKAGE_ID_IS_NULL);
            }
            setMealDto.setId(id);
            RestStatus status = elasticsearchService.updateSetMealDto(setMealDto);
            if (status.getStatus() == RestStatus.OK.getStatus()) {
                return ApiResult.succ();
            } else {
                return ApiResult.fail(ProductErrorCode.UPDATE_SET_MEAL_FROM_ELASTICSEARCH_IS_ERROR, status.name());
            }
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.UPDATE_SET_MEAL_FROM_ELASTICSEARCH_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.UPDATE_SET_MEAL_FROM_ELASTICSEARCH_IS_ERROR);
        }
    }

    /**
     * @param setMeal  套餐查询
     * @param userInfo 用户信息
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.common.util.support.Pagination<com.hsgene.product
     * .dto.SetMealDto>>
     * @description 根据查询条件查询套餐信息
     * @author maodi
     * @createDate 2018/10/25 10:03
     */
    @GetMapping
    public ApiResult<Pagination<SetMealDto>> search(QuerySetMealDto setMeal, @FromSession UserInfo userInfo) {
        try {
            String userId = setMeal.getUserId();
            if (StringUtils.isBlank(userId)) {
                if (userInfo != null) {
                    String infoUserId = userInfo.getUserId();
                    if (StringUtils.isBlank(infoUserId)) {
                        return ApiResult.fail(CommonErrorCode.USER_ID_IS_NULL);
                    } else {
                        setMeal.setUserId(infoUserId);
                    }
                } else {
                    return ApiResult.fail(CommonErrorCode.USER_INFO_IS_NULL);
                }
            }
            return elasticsearchService.search(setMeal);
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.SEARCH_SET_MEAL_FROM_ELASTICSEARCH_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.SEARCH_SET_MEAL_FROM_ELASTICSEARCH_IS_ERROR);
        }
    }

    /**
     * @param id 套餐id
     * @return com.hsgene.common.util.result.ApiResult<com.hsgene.product.dto.SetMealDto>
     * @description 根据套餐id获取套餐信息
     * @author maodi
     * @createDate 2018/10/29 16:02
     */
    @GetMapping("{package_id}")
    public ApiResult<SetMealDto> searchById(@PathVariable("package_id") String id) {
        try {
            if (StringUtils.isBlank(id)) {
                return ApiResult.fail(ProductErrorCode.PACKAGE_ID_IS_NULL);
            }
            return ApiResult.succ(elasticsearchService.searchById(id));
        } catch (Exception e) {
            LOGGER.error(ProductErrorCode.SEARCH_BY_PACKAGE_ID_IS_ERROR.getMessage(), e);
            return ApiResult.fail(ProductErrorCode.SEARCH_BY_PACKAGE_ID_IS_ERROR);
        }
    }

    /**
     * 根据名称修改
     *
     * @param queryName
     * @param queryValue
     * @param idOrCode
     * @return
     * @author FX
     * @date 2019/1/4 10:45
     */
    @PutMapping("relation")
    public ApiResult<NullObject> updateByQuery(String queryName, String queryValue, String idOrCode) {
        BulkByScrollTask.Status status = elasticsearchService.updateByQuery(queryName, queryValue, idOrCode);
        return ApiResult.succ();
    }

}
